<template>
  <div class="flex gap-8px items-center">
    <!-- 是否启用 -->
    <t-switch v-model="order.isEnable">
      <template #label="slotProps">{{ slotProps.value ? "启用" : "禁用" }}</template>
    </t-switch>
    <t-select
      v-model="order.field"
      filterable
      creatable
      clearable
      placeholder="请选择排序字段"
      style="width: 250px"
    >
      <t-option
        v-for="(field, idx1) in fields"
        :key="idx1"
        :label="field.name"
        :value="field.name"
      ></t-option>
    </t-select>
    <t-select v-model="order.type" filterable placeholder="请选择排序条件" style="width: 80px">
      <t-option label="asc" value="asc"></t-option>
      <t-option label="desc" value="desc"></t-option>
    </t-select>
    <t-button theme="primary" shape="square" @click="add()">
      <template #icon>
        <icon-plus />
      </template>
    </t-button>
    <t-button theme="danger" shape="square" @click="remove(order.id)">
      <template #icon>
        <icon-minus />
      </template>
    </t-button>
    <t-button theme="success" shape="square" @click="search()">
      <template #icon>
        <icon-search />
      </template>
    </t-button>
  </div>
</template>
<script lang="ts" setup>
import BaseOrder from "@/entity/BaseOrder";
import { BaseSearchInstanceResult } from "@/hooks";
import { useIndexStore } from "@/store";

const props = defineProps({
  modelValue: Object as PropType<BaseOrder>,
  tab: {
    type: Object as PropType<BaseSearchInstanceResult>,
    required: true
  }
});
const emits = defineEmits(["update:modelValue", "add", "remove"]);

const order = ref<BaseOrder>(
  props.modelValue
    ? props.modelValue
    : {
        id: new Date().getTime(),
        field: "",
        type: "asc",
        isEnable: true
      }
);

watch(
  () => props.modelValue,
  (value) => {
    if (value) {
      order.value = value;
    }
  }
);
watch(
  () => order.value,
  (value) => {
    emits("update:modelValue", value);
  },
  { deep: true }
);

const fields = computed(() => {
  const { fieldMap } = useIndexStore();
  return fieldMap.get(props.tab.index.value) || [];
});

function add() {
  emits("add");
}

function remove(id: number) {
  emits("remove", id);
}

function search() {
  props.tab.run();
}
</script>
<style scoped></style>
